//  UserTask 自定义配置：1. 审批人与提交人为同一人时; 2. 审批人拒绝时; 3. 审批人为空时
import {
	ASSIGN_START_USER_HANDLER_TYPES,
	RejectHandlerType,
	REJECT_HANDLER_TYPES,
	ASSIGN_EMPTY_HANDLER_TYPES,
	AssignEmptyHandlerType
} from "@/components/SimpleProcessDesignerV2/src/consts";
import { BasicForm, useForm, FormSchema } from "@/components/Form";
import { getSimpleUserList } from "@/api/system/user";
import { useContext, useEffect } from "react";
import PanelContext from "../PanelContext";

export default function ElementCustomCOnfig(props: any) {
	const contextState = useContext(PanelContext);
	const prefix = contextState.prefix;

	// 审批人与提交人为同一人时
	let assignStartUserHandlerTypeEl: Recordable;
	// 审批人拒绝时
	let rejectHandlerTypeEl: Recordable;
	let returnNodeIdEl: Recordable;
	let returnTaskList = [];
	// 审批人为空时
	let assignEmptyHandlerTypeEl: Recordable;
	let assignEmptyUserIdsEl: Recordable;

	let elExtensionElements;
	let otherExtensions: any[] = [];
	let bpmnElement: any;
	const bpmnInstances = () => (window as any)?.bpmnInstances;

	const schemas: FormSchema[] = [
		{
			label: "审批人拒绝时",
			field: "d1",
			component: "Divider",
			// icon: 'radix-icons:divider-horizontal',
			colProps: { span: 24 }
			// componentProps: {
			//   orientation: 'center',
			//   dashed: true,
			// },
		},
		{
			field: "rejectHandlerType",
			component: "RadioGroup",
			componentProps: {
				options: REJECT_HANDLER_TYPES,
				onChange: () => updateElementExtensions()
			}
		},
		{
			label: "驳回节点",
			field: "returnNodeId",
			component: "Select",
			ifShow: ({ values }) => values.rejectHandlerType == RejectHandlerType.RETURN_USER_TASK,
			componentProps: {
				options: [],
				fieldNames: {
					label: "name",
					value: "id"
				},
				onChange: () => updateElementExtensions()
			}
		},
		{
			label: "审批人为空时",
			field: "d2",
			component: "Divider",
			colProps: { span: 24 }
		},
		{
			field: "assignEmptyHandlerType",
			component: "RadioGroup",
			componentProps: {
				options: ASSIGN_EMPTY_HANDLER_TYPES,
				onChange: () => updateElementExtensions()
			}
		},
		{
			label: "指定用户",
			field: "assignEmptyHandlerUserIds",
			component: "ApiSelect",
			ifShow: ({ values }) => values.assignEmptyHandlerType == AssignEmptyHandlerType.ASSIGN_USER,
			componentProps: {
				api: getSimpleUserList,
				mode: "multiple",
				labelField: "nickname",
				valueField: "id",
				onChange: () => updateElementExtensions()
			}
		},
		{
			label: "审批人与提交人为同一人时",
			field: "d3",
			component: "Divider",
			colProps: { span: 24 }
		},
		{
			field: "assignStartUserHandlerType",
			component: "RadioGroup",
			componentProps: {
				options: ASSIGN_START_USER_HANDLER_TYPES,
				onChange: () => updateElementExtensions()
			}
		}
	];
	const [registerForm, { updateSchema, setFieldsValue, getFieldsValue }] = useForm({
		schemas,
		showActionButtonGroup: false,
		// labelWidth: 80,
		baseColProps: { span: 24 }
	});

	/** Function */

	const resetCustomConfigList = () => {
		// 获取可回退的列表
		returnTaskList = findAllPredecessorsExcludingStart(bpmnElement.id, bpmnInstances().modeler);

		// 获取元素扩展属性 或者 创建扩展属性
		elExtensionElements =
			bpmnElement.businessObject?.extensionElements ?? bpmnInstances().moddle.create("bpmn:ExtensionElements", { values: [] });

		// 审批人与提交人为同一人时
		assignStartUserHandlerTypeEl =
			elExtensionElements.values?.filter(ex => ex.$type === `${prefix}:AssignStartUserHandlerType`)?.[0] ||
			bpmnInstances().moddle.create(`${prefix}:AssignStartUserHandlerType`, { value: 1 });

		// 审批人拒绝时
		rejectHandlerTypeEl =
			elExtensionElements.values?.filter(ex => ex.$type === `${prefix}:RejectHandlerType`)?.[0] ||
			bpmnInstances().moddle.create(`${prefix}:RejectHandlerType`, { value: 1 });
		returnNodeIdEl =
			elExtensionElements.values?.filter(ex => ex.$type === `${prefix}:RejectReturnTaskId`)?.[0] ||
			bpmnInstances().moddle.create(`${prefix}:RejectReturnTaskId`, { value: "" });

		// 审批人为空时
		assignEmptyHandlerTypeEl =
			elExtensionElements.values?.filter(ex => ex.$type === `${prefix}:AssignEmptyHandlerType`)?.[0] ||
			bpmnInstances().moddle.create(`${prefix}:AssignEmptyHandlerType`, { value: 1 });

		assignEmptyUserIdsEl =
			elExtensionElements.values?.filter(ex => ex.$type === `${prefix}:AssignEmptyUserIds`)?.[0] ||
			bpmnInstances().moddle.create(`${prefix}:AssignEmptyUserIds`, { value: "" });

		let assignEmptyUserIds = "";
		if (assignEmptyUserIdsEl.value) {
			assignEmptyUserIds = assignEmptyUserIdsEl.value.split(",").map(item => {
				// 如果数字超出了最大安全整数范围，则将其作为字符串处理
				let num = Number(item);
				return num > Number.MAX_SAFE_INTEGER || num < -Number.MAX_SAFE_INTEGER ? item : num;
			});
		}

		// 保留剩余扩展元素，便于后面更新该元素对应属性
		otherExtensions =
			elExtensionElements.values?.filter(
				ex =>
					ex.$type !== `${prefix}:AssignStartUserHandlerType` &&
					ex.$type !== `${prefix}:RejectHandlerType` &&
					ex.$type !== `${prefix}:RejectReturnTaskId` &&
					ex.$type !== `${prefix}:AssignEmptyHandlerType` &&
					ex.$type !== `${prefix}:AssignEmptyUserIds`
			) ?? [];

		console.log("ElementCustomConfig-resetCustomConfigList", elExtensionElements.values, returnNodeIdEl, returnNodeIdEl.value);
		// 更新表单
		setFieldsValue({
			assignStartUserHandlerType: +assignStartUserHandlerTypeEl.value,
			rejectHandlerType: +rejectHandlerTypeEl.value,
			returnNodeId: returnNodeIdEl.value,
			assignEmptyHandlerType: +assignEmptyHandlerTypeEl.value,
			assignEmptyUserIds
		});
		updateSchema({
			field: "returnNodeId",
			componentProps: { options: returnTaskList }
		});
	};

	const updateElementExtensions = async () => {
		const values = await getFieldsValue();
		assignStartUserHandlerTypeEl.value = values.assignStartUserHandlerType;
		rejectHandlerTypeEl.value = values.rejectHandlerType;
		returnNodeIdEl.value = values.returnNodeId;
		assignEmptyHandlerTypeEl.value = values.assignEmptyHandlerType;
		assignEmptyUserIdsEl.value = values.assignEmptyUserIds;
		const extensions = bpmnInstances().moddle.create("bpmn:ExtensionElements", {
			values: [
				...otherExtensions,
				assignStartUserHandlerTypeEl,
				rejectHandlerTypeEl,
				returnNodeIdEl,
				assignEmptyHandlerTypeEl,
				assignEmptyUserIdsEl
			]
		});
		bpmnInstances().modeling.updateProperties(bpmnElement, {
			extensionElements: extensions
		});
		console.log("ElementCustomConfig-updateElementExtensions", values, bpmnInstances()?.bpmnElement);
	};

	function findAllPredecessorsExcludingStart(elementId, modeler) {
		const elementRegistry = modeler.get("elementRegistry");
		const allConnections = elementRegistry.filter(element => element.type === "bpmn:SequenceFlow");
		const predecessors = new Set(); // 使用 Set 来避免重复节点

		// 检查是否是开始事件节点
		function isStartEvent(element) {
			return element.type === "bpmn:StartEvent";
		}

		function findPredecessorsRecursively(element) {
			// 获取与当前节点相连的所有连接
			const incomingConnections = allConnections.filter(connection => connection.target === element);

			incomingConnections.forEach(connection => {
				const source = connection.source; // 获取前置节点

				// 只添加不是开始事件的前置节点
				if (!isStartEvent(source)) {
					predecessors.add(source.businessObject);
					// 递归查找前置节点
					findPredecessorsRecursively(source);
				}
			});
		}

		const targetElement = elementRegistry.get(elementId);
		if (targetElement) {
			findPredecessorsRecursively(targetElement);
		}

		return Array.from(predecessors); // 返回前置节点数组
	}

	/** Effect */

	useEffect(() => {
		bpmnElement = bpmnInstances().bpmnElement;
		props.id && props.id.length && resetCustomConfigList();
	}, [props.id]);

	return <BasicForm register={registerForm} />;
}
